package timbap.visualizer.impl.context.messaging;

import timbap.visualizer.api.model.TimeCode;
import timbap.visualizer.api.model.MappedTimeCodeInterpolation;
import timbap.visualizer.api.context.messaging.InterpolatingTimeCodePublisher;
import oscP5.OscMessage;

public class InterpolatingOscTimeCodePublisherImpl extends OscTimeCodePublisherImpl
                                                   implements InterpolatingTimeCodePublisher {

    private static final float VELOCITY_FACTOR_ADJUSTMENT = 18;

    private MappedTimeCodeInterpolation interpolatedTimeCode;    

    public InterpolatingOscTimeCodePublisherImpl(Class<? extends TimeCode> pTimeCodeClass) {
        super(pTimeCodeClass);
    }

    public void setTimeCodeInterpolation(int pItemCount, int pPlaylistSize, float pVelocityFactor) {
        if (pPlaylistSize > 0 && pItemCount > 0) {
            float tNormalizingVelocityFactor =
                (VELOCITY_FACTOR_ADJUSTMENT * pVelocityFactor * pItemCount) / pPlaylistSize;
            interpolatedTimeCode = new MappedTimeCodeInterpolation(tNormalizingVelocityFactor, getTimeCode());
        } else {
            interpolatedTimeCode = null;
        }
    }

    public void oscEvent(OscMessage pOscMessage) {
        // workaround to make registration of event method at OscP5 work for this subclass
        super.oscEvent(pOscMessage);
    }

    public void publishTimeCode(TimeCode pTimeCode) {
        if (interpolatedTimeCode != null) {
            interpolatedTimeCode.updateInterpolatedTimeCode();
            super.publishTimeCode(interpolatedTimeCode);
        } else {
            super.publishTimeCode(pTimeCode);
        }
    }

}
